package com.keon.jianbao.ui.activity;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.keon.jianbao.AppContext;
import com.keon.jianbao.R;
import com.keon.jianbao.api.Api;
import com.keon.jianbao.api.SimpleHandler;
import com.keon.jianbao.base.BaseActivity;
import com.keon.jianbao.bean.Result;
import com.keon.jianbao.enu.PasswordActivtyType;
import com.keon.jianbao.util.JsonUtils;
import com.keon.jianbao.util.StringUtils;

import org.apache.http.Header;
import org.json.JSONException;

import java.util.HashMap;

import butterknife.Bind;

/**
 * Created by keon on 2015/9/6.
 */
public class RegisterActivity extends BaseActivity {

    @Bind(R.id.register_mobile)
    EditText etMobile;
    @Bind(R.id.register_captcha)
    EditText etCaptcha;
    @Bind(R.id.register_next)
    Button bNext;
    @Bind(R.id.register_captcha_btn)
    Button bCaptcha;

    int type;
    String code;

    SimpleHandler checkMobileHandler = new SimpleHandler(this) {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//            super.onSuccess(statusCode, headers, responseBody);
            Result result = null;
            try {
                result = new Result(responseBody);
                if (type == PasswordActivtyType.REGISTER.getValue() || type == PasswordActivtyType.BIND.getValue()) {
                    if (result.getStatus() > 0) {
                        showWaitDialog();
                        Api.msg_code(etMobile.getText().toString(), msgCodeHandler);
                    } else {
                        showToast(result.getTips());
                    }


                } else if (type == PasswordActivtyType.FORGET.getValue()) {
                    if (result.getStatus() == 0) {
                        showWaitDialog();
                        Api.msg_code(etMobile.getText().toString(), msgCodeHandler);
                    } else {
                        showToast("该手机号尚未注册");
                    }
                } else {

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    SimpleHandler msgCodeHandler = new SimpleHandler(this) {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            super.onSuccess(statusCode, headers, responseBody);
            Result result = null;
            try {
                result = new Result(responseBody);
                if (result.getStatus() > 0) {
                    showToast(result.getTips());
                    code = JsonUtils.fromJson(result.getContent(), HashMap.class).get("code").toString();

                    TimeCount timeCount = new TimeCount(60000, 1000);
                    timeCount.start();
                } else {
//                    RegisterActivity.showToast(result.getTips());
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    SimpleHandler bindMobileHandler = new SimpleHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            super.onSuccess(statusCode, headers, responseBody);
            Result result = null;
            try {
                result = new Result(responseBody);
                if (result.getStatus() > 0) {
                    showToast("绑定成功");
                } else {
                    showToast("绑定失败，请重试");
                    AppContext.getInstance().cleanLoginInfo();
//                    RegisterActivity.showToast(result.getTips());
                }
            } catch (JSONException e) {
                e.printStackTrace();
                showToast("绑定失败，请重试");
                AppContext.getInstance().cleanLoginInfo();
            }
            onBackPressed();
        }
    };


    @Override
    protected int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    protected int getToolBarTitle() {
        if (type == PasswordActivtyType.REGISTER.getValue()) {
            return R.string.register;
        } else if (type == PasswordActivtyType.FORGET.getValue()) {
            return R.string.forget_password;
        } else if (type == PasswordActivtyType.BIND.getValue()) {
            return R.string.bind_mobile;
        }
        return R.string.register;
    }

    @Override
    public void initView() {
        bNext.setOnClickListener(this);
        bCaptcha.setOnClickListener(this);

        Bundle bundle = getIntent().getExtras();
        type = bundle.getInt("type");

        if (type != PasswordActivtyType.BIND.getValue()) {
            setRightTitle();
        }
    }

    @Override
    public void initData() {

        bindMobileHandler.setContext(this);
        checkMobileHandler.setContext(this);
        msgCodeHandler.setContext(this);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.register_captcha_btn:
                if (checkMobile()) {
                    RegisterActivity.this.showWaitDialog();
                    Api.checkMobile(etMobile.getText().toString(), checkMobileHandler);
                }
                break;
            case R.id.register_next:
                if (check()) {
                    Bundle bundle = new Bundle();
                    bundle.putString("mobile", etMobile.getText().toString());
                    if (type != PasswordActivtyType.BIND.getValue()) {
                        bundle.putInt("type", type);
                        jump(RegisterActivity2.class, bundle);
                    } else {
                        showWaitDialog();
                        Api.alter_info(AppContext.getInstance().getProperty("user.code"), "", "", "", "", etMobile.getText().toString(), "", bindMobileHandler);
                    }
                    break;
                }
        }
    }

    private void setRightTitle() {
        TextView v = new TextView(this);
        v.setTextColor(getResources().getColor(R.color.white));
        v.setPadding(0, 0, 20, 0);
        v.setText("(1/2)");
        setRightView(v);
    }

    private boolean checkMobile() {
        String m = etMobile.getText().toString();
        if (StringUtils.isEmpty(m)) {
            showToast(R.string.register_mobile_error_null);
            return false;
        }
        if (!StringUtils.isMobile(m)) {
            showToast(R.string.register_mobile_error_wrong);
            return false;
        }
        return true;
    }

    private boolean check() {
        if (!checkMobile()) {
            return false;
        }
        String c = etCaptcha.getText().toString();

        if (StringUtils.isEmpty(c)) {
            showToast(R.string.register_captcha_error_null);
            return false;
        } else if (!c.equals(code)) {
            showToast(R.string.register_captcha_error_wrong);
            return false;
        }

        return true;
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);//参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {//计时完毕时触发
            bCaptcha.setText(R.string.register_captcha_btn);
            bCaptcha.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {//计时过程显示
            bCaptcha.setClickable(false);
            bCaptcha.setText(millisUntilFinished / 1000 + "秒");
        }
    }


}
